import logging
import os
import shutil
import datetime
import re
from django.core.management.base import BaseCommand
from django.db import connection
from conf.env import *
logger = logging.getLogger(__name__)
from application.settings import BASE_DIR


class Command(BaseCommand):
    """
    创建App命令:
    python manage.py createapp app名
    """

    def add_arguments(self, parser):
        parser.add_argument('app_name', nargs='*', type=str, )

    def handle(self, *args, **options):
        app_name = options.get('app_name')
        for name in app_name:
            print(f"开始创建app")           
            AppClass=name.capitalize()
            app_path = os.path.join(BASE_DIR, name)
             # 判断app是否存在
            if os.path.exists(app_path):
                print(f"创建失败，App {name} 已存在！")
                break
            #生成前端文件
            Webpath=os.path.abspath(os.path.join(BASE_DIR, "../web"))
            viewsfolder=os.path.join(Webpath, "src","views",name)
            Sapifile = os.path.join(Webpath, "src","template",'api.js')            
            Tapifile = os.path.join(Webpath, "src","views",name,'api.js')
            Scrudfile = os.path.join(Webpath, "src","template",'crud.js')            
            Tcrudfile = os.path.join(Webpath, "src","views",name,'crud.js')           
            Svuefile = os.path.join(Webpath, "src","template",'index.vue')            
            Tvuefile = os.path.join(Webpath, "src","views",name,'index.vue')

             # 判断views是否存在
            if os.path.exists(viewsfolder):
                print(f"创建{name} views，已存在！")
                break
            else:
                os.makedirs(viewsfolder)
                shutil.copyfile(Sapifile,Tapifile)
                shutil.copyfile(Scrudfile,Tcrudfile)
                shutil.copyfile(Svuefile,Tvuefile)
                with open(Tapifile, 'r', encoding='UTF-8') as f:                
                    alllines=f.readlines()
                    f.close()
                with open(Tapifile, 'w', encoding='UTF-8') as f:
                    for eachline in alllines:
                        a=re.sub('appname',name,eachline)                  
                        f.writelines(a)
                    f.close()

                with open(Tvuefile, 'r', encoding='UTF-8') as f:                
                    alllines=f.readlines()
                    f.close()
                with open(Tvuefile, 'w', encoding='UTF-8') as f:
                    for eachline in alllines:
                        a=re.sub('appname',name,eachline)             
                        f.writelines(a)
                    f.close()
               


            source_path = os.path.join(BASE_DIR, "dvadmin", "template")
            target_path = app_path
            if not os.path.exists(target_path):
                # 如果目标路径不存在原文件夹的话就创建
                os.makedirs(target_path)
            if os.path.exists(source_path):
                # 如果目标路径存在原文件夹的话就先删除
                shutil.rmtree(target_path)
            shutil.copytree(source_path, target_path)
            # 修改app中的apps 内容
            content = f"""from django.apps import AppConfig


class {AppClass}Config(AppConfig):
    name = '{name}'
    verbose_name = "{name}App"
"""
            with open(os.path.join(app_path, "apps.py"), 'w', encoding='UTF-8') as f:
                f.write(content)
                f.close() 
  
            with open(os.path.join(app_path, "serializers.py"), 'r', encoding='UTF-8') as f:                
                alllines=f.readlines()
                f.close()
            with open(os.path.join(app_path, "serializers.py"), 'w', encoding='UTF-8') as f:
                for eachline in alllines:
                    a=re.sub('appname',name,eachline)
                    a=re.sub('AppClass',AppClass,a)
                    f.writelines(a)
                f.close()
            with open(os.path.join(app_path, "urls.py"), 'r', encoding='UTF-8') as f:                
                alllines=f.readlines()
                f.close()
            with open(os.path.join(app_path, "urls.py"), 'w', encoding='UTF-8') as f:
                for eachline in alllines:
                    a=re.sub('appname',name,eachline)
                    a=re.sub('AppClass',AppClass,a)
                    f.writelines(a)
                f.close()
            with open(os.path.join(app_path, "views.py"), 'r', encoding='UTF-8') as f:                
                alllines=f.readlines()
                f.close()
            with open(os.path.join(app_path, "views.py"), 'w', encoding='UTF-8') as f:
                for eachline in alllines:
                    a=re.sub('appname',name,eachline)
                    a=re.sub('AppClass',AppClass,a)
                    f.writelines(a)
                f.close()
            with open(os.path.join(app_path, "models.py"), 'r', encoding='UTF-8') as f:                
                alllines=f.readlines()
                f.close()
            with open(os.path.join(app_path, "models.py"), 'w', encoding='UTF-8') as f:
                for eachline in alllines:
                    a=re.sub('appname',name,eachline)
                    a=re.sub('AppClass',AppClass,a)
                    f.writelines(a)
                f.close()

            # 注册app到 settings.py 中
            injection(os.path.join(BASE_DIR, "application", "settings.py"), f"    '{name}',\n", "INSTALLED_APPS","]")

            # 注册app到 urls.py 中
            injection(os.path.join(BASE_DIR, "application", "urls.py"), f"        path('',include('{name}.urls')),\n", "urlpatterns = (",
                      "        ]")

            print(f"后台创建 {name} App成功")

            print(f"添加菜单")
            #添加菜单
            #INSERT ( `modifier`,  `dept_belong_id`,  ``,  `create_datetime`,  `menuType`,  `icon`,  `name`,  `orderNum`,  `isFrame`,  `web_path`,  `component_path`,  `interface_path`,  `interface_method`,  `perms`,  `status`,  `visible`,  `isCache`,  `creator_id`,  `parentId_id`) VALUES() INTO permission_menu
            with connection.cursor() as cur:
                mlsql=f"""INSERT INTO {TABLE_PREFIX}system_menu (modifier,dept_belong_id,update_datetime,create_datetime,icon,name,sort,is_link,is_catalog,web_path,component,component_name,status,cache,visible,creator_id) 
 VALUES('2', 1,'{datetime.datetime.now()}','{datetime.datetime.now()}','heartbeat','{name}',6,0,0,'/{name}','{name}/index','{name}',1,0,1,2) """
                cur.execute(mlsql)
                fid=cur.lastrowid
                mlsql=f"""INSERT INTO {TABLE_PREFIX}system_menu_button (modifier,dept_belong_id,update_datetime,create_datetime,name,value,api,method,menu_id) 
 VALUES('2', 1,'{datetime.datetime.now()}','{datetime.datetime.now()}','新增','Create','/api/{name}/',1,{fid}) """
                cur.execute(mlsql)
                mlsql=f"""INSERT INTO {TABLE_PREFIX}system_menu_button (modifier,dept_belong_id,update_datetime,create_datetime,name,value,api,method,menu_id) 
 VALUES('2', 1,'{datetime.datetime.now()}','{datetime.datetime.now()}','编辑','Update','/api/{name}/{{id}}/',2,{fid}) """
                cur.execute(mlsql)
                mlsql=f"""INSERT INTO {TABLE_PREFIX}system_menu_button (modifier,dept_belong_id,update_datetime,create_datetime,name,value,api,method,menu_id) 
 VALUES('2', 1,'{datetime.datetime.now()}','{datetime.datetime.now()}','删除','Delete','/api/{name}/{{id}}/',3,{fid}) """
                cur.execute(mlsql)
                mlsql=f"""INSERT INTO {TABLE_PREFIX}system_menu_button (modifier,dept_belong_id,update_datetime,create_datetime,name,value,api,method,menu_id) 
 VALUES('2', 1,'{datetime.datetime.now()}','{datetime.datetime.now()}','查询','Search','/api/{name}/',0,{fid}) """
                cur.execute(mlsql)
                mlsql=f"""INSERT INTO {TABLE_PREFIX}system_menu_button (modifier,dept_belong_id,update_datetime,create_datetime,name,value,api,method,menu_id) 
 VALUES('2', 1,'{datetime.datetime.now()}','{datetime.datetime.now()}','详情','Retrieve','/api/{name}/{{id}}/',0,{fid}) """
                cur.execute(mlsql)

                
            print(f"{name} 菜单添加成功")
                
                




def injection(file_path, insert_content, startswith, endswith):
    with open(file_path, "r+", encoding="utf-8") as f:
        data = f.readlines()
        with open(file_path, 'w', encoding='UTF-8') as f1:
            is_INSTALLED_APPS = False
            is_insert = False
            for content in data:
                # 判断文件是否 INSTALLED_APPS 开头
                if not is_insert and content.startswith(startswith):
                    is_INSTALLED_APPS = True
                if not is_insert and content.startswith(endswith) and is_INSTALLED_APPS:
                    # 给前一行插入数据
                    content = insert_content + content
                    is_insert = True
                f1.writelines(content)
